<template>
  <main v-if="statusCode === 200">
    <Row>
      <left-module 
        :blogList="blogList"
        :totalBlog="totalBlog"
        :currentPage="currentPage"
        :pageSize="pageSize"
        @changePage="changePage"
      ></left-module>
      <right-module></right-module>
    </Row>
  </main>
  <not-found v-else></not-found>
</template>

<script>
import { findBlogByTagId } from 'service'

export default {
  name: 'Tag',
  data() {
    return {
      totalBlog: 0,
      currentPage: +this.$route.query.page || 1,
      pageSize: 12,
      blogList: [],
      tagName: '',
      flag: true,
      statusCode: 200
    }
  },
  created() {
    this.getTag()
  },
  computed: {
    tagList() {
      return this.$store.getters['blog/tags']
    },
  },
  methods: {
    async getTag() {
      let id = this.$route.params['id']
      this.tagList.forEach(item => {
        if (id == item.id) {
          this.tagName = item.name
        }
      })
      let res = await findBlogByTagId(this.currentPage, this.pageSize, id)
      this.statusCode = res.data.statusCode 
      if (this.statusCode === 200) {
        this.blogList = res.data.data.list
        this.totalBlog = res.data.data.total
        document.title = `${this.tagName} - ${this.documentTitle}`
      } 
    },
    async changePage(currentPage) {
      this.currentPage = currentPage
      await this.getTag()
      this.flag = false
      let query = currentPage === 1 ? {} : { page: currentPage }
      this.$router.push({ name: 'tag', query: query })
    }
  },
  watch: {
    $route(to, from) {
      if (this.flag && to.name === 'tag') {
        this.currentPage = +to.query.page || 1
        this.getTag()
      }
      this.flag = true
    }
  },
  components: {
    "left-module": () => import("components/homePage/LeftModule"),
    "right-module": () => import("components/homePage/RightModule"),
  }
}
</script>

<style lang='scss' scoped>
</style>